/*
 * @Author: Zyunchao 18651805393@163.com
 * @Date: 2022-11-30 11:07:26
 * @LastEditors: Zyunchao 18651805393@163.com
 * @LastEditTime: 2023-02-15 13:27:11
 * @FilePath: /micro-temp-monorepo/_core/api/index.ts
 * @Description: 加载所有请求模块的加载器
 */
import type { App } from 'vue'
import type { RequestConfig } from '@jsjn/types/Request'
import type { BaseResponse } from '@jsjn/types/Response'
import { createRequestByMapping } from './base'
import packInfo from '@ROOT/package.json'

type Apis = {
    [key: string]: {
        [key: string]: (params?: any, replace?: Record<string, string | number>) => Promise<BaseResponse>
    }
}

/**
 * 根据固定的文件格式 modules 目录，处理成 api 方法列表
 * @param files
 * @returns
 */
export function disposeApiModulesByRequireContext(files: __WebpackModuleApi.RequireContext): Apis {
    const allApiMapping: string[] = []
    return files.keys().reduce((apis: Apis, path: string) => {
        let key = path.replace(/(.*\/)*([^.]+).*/gi, '$2')
        const module: RequestConfig[] = files(path).default

        // 系统内唯一性校验
        module.forEach((reqConfig) => {
            const onlyKey = `${packInfo.name}:{${reqConfig.api}}:${reqConfig.method}${
                reqConfig.paramType ? ':' + reqConfig.paramType : ''
            }`

            if (!allApiMapping.some((k) => k === onlyKey)) {
                allApiMapping.push(onlyKey)
            } else {
                throw new Error(`存在相同的配置 ** ${onlyKey}`)
            }
        })

        apis[key] = createRequestByMapping(module)
        return apis
    }, {})
}

export const apis = disposeApiModulesByRequireContext(
    require.context('./modules', false, /\.api\.ts$/)
)
export default (app: App) => {
    app.config.globalProperties.$api = apis
}
